package com.example.exam.controller;

import com.example.exam.dto.ExamUserDTO;
import com.example.exam.entity.ExamPaper;
import com.example.exam.entity.ExamPaperAnswer;
import com.example.exam.entity.ExamUser;
import com.example.exam.service.ExamPaperAnswerService;
import com.example.exam.service.ExamPaperService;
import com.example.exam.service.ExamUserService;
import com.example.exam.util.ResultVOUtil;
import com.example.exam.vo.ExamPaperVO;
import com.example.exam.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author shishuqian
 * date 2021/4/27
 * time 15:39
 * 试卷api
 **/
@RestController
@RequestMapping("/examPaper")
@Api(value = "试卷controller",tags = {"试卷访问接口"})
public class ExamPaperController {

    @Autowired
    private ExamPaperService examPaperService;

    @Autowired
    private ExamPaperAnswerService examPaperAnswerService;

    @Autowired
    private ExamUserService examUserService;


    @ApiOperation(value = "根据id查询试卷")
    @GetMapping("/findById/{id}")
    public ResultVO findById(@PathVariable("id")Integer id){

       return ResultVOUtil.success(examPaperService.findById(id));
    }

    /**
     * 每创建一题，保存一次
     * 保存完试卷后，将试卷信息返回
     * @param examPaper
     */
    @ApiOperation(value = "保存试卷，每创建一题，保存一次")
    @PostMapping("/save")
    public ResultVO save(@RequestBody ExamPaper examPaper){
        examPaper.setCreateTime(new Date());  //设置创建时间
        examPaper.setDeleted(false);
        if (examPaper.getStartTime()==null || examPaper.getEndTime()==null){ //不限时试卷默认不发布
            examPaper.setStatus(false);
        }else {  //限时试卷默认发布
            examPaper.setStatus(true);
        }
        int examPaperId = examPaperService.save(examPaper);
        ExamPaper examPaper1 = examPaperService.findById(examPaperId);
        return ResultVOUtil.success(examPaper1);
    }

    @ApiOperation(value = "查询用户创建的所有试卷,分页查询")
    @GetMapping("/findAllByUserId/{user_id}/{page}/{size}")
    public ResultVO findAllByUserId(@PathVariable("user_id") Integer user_id,
                                    @PathVariable("page") Integer page,
                                    @PathVariable("size") Integer size){
        Page<ExamPaper> examPaperVOList = examPaperService.findAllByUserId(user_id,page,size);

        return ResultVOUtil.success(examPaperVOList);
    }

    /**
     * 创建完试卷后一次保存完毕
     * @param examPaper
     */
    @ApiOperation(value = "保存试卷，创建完保存")
    @PostMapping("/saveAll")
    public void saveAll(@RequestBody ExamPaper examPaper){
        examPaper.setCreateTime(new Date());  //设置创建时间
        examPaper.setDeleted(false);
        examPaperService.save(examPaper);
    }

    @ApiOperation(value = "更新试卷")
    @PutMapping("/update")
    public void update(@RequestBody ExamPaper examPaper){
        examPaper.setCreateTime(new Date());  //设置创建时间
        examPaper.setDeleted(false);
        if (examPaper.getStartTime()==null || examPaper.getEndTime()==null){ //不限时试卷默认不发布
            examPaper.setStatus(false);
        }else {  //限时试卷默认发布
            examPaper.setStatus(true);
        }
        examPaperService.update(examPaper);
    }

    @ApiOperation(value = "根据id删除试卷")
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id")Integer id){
        examPaperService.deleteById(id);
    }

    //发布/停止试卷
    @PutMapping("/releaseOrStop/{id}")
    public void release(@PathVariable("id") Integer id){
        examPaperService.release(id);
    }

    //开始做卷
    @GetMapping("/fill/{userId}/{examPaperId}")
    public ResultVO fillPaper(@PathVariable("userId") Integer userId,
                              @PathVariable("examPaperId") Integer examPaperId){

        //正常情况只会有一条数据，为方便测试可能会产生多份答题卷，所以使用集合，取第一个数据
        List<ExamPaperAnswer> paperList = examPaperAnswerService.findByUserIdAndExamPaperId(userId, examPaperId);

        if (!paperList.isEmpty()){
            ExamPaperAnswer answer = paperList.get(0);
            if (answer.getFinishStatus() != null && answer.getFinishStatus()){  //已完成提交
                return ResultVOUtil.error("你已填写过，不可重复提交...");
            }

        }
        ExamPaper examPaper = examPaperService.findById(examPaperId);
        if (examPaper==null){
            return ResultVOUtil.error("该试卷不存在...");
        }

        if (examPaper.getSelectPeople() != null && examPaper.getSelectPeople()) { //如果是选人试卷
            ExamUser examUser = examUserService.findByExamPaperIdAndUserId(examPaperId, userId);
            if (examUser == null){
                return ResultVOUtil.error("该试卷为指定试卷,你不能填写此试卷...");
            }
        }

        Date now = new Date(); //获取当前系统时间
        if (examPaper.getStatus()==null || !examPaper.getStatus()){
            return ResultVOUtil.error("试卷未发布，请等待...");
        }
        if (examPaper.getStatus()){ //试卷已发布

            if (examPaper.getStartTime()==null && examPaper.getEndTime()==null){ //不限时试卷，直接返回
                return ResultVOUtil.success(examPaper);
            }else if (examPaper.getStartTime()==null){ //无开始时间，则判断结束时间
                if (now.after(examPaper.getEndTime())){
                    return ResultVOUtil.error("考试已经结束...");
                }else {
                    return ResultVOUtil.success(examPaper);
                }
            }else if (examPaper.getEndTime()==null){ //无结束时间，则判断开始时间
                if (now.before(examPaper.getStartTime())){
                    return ResultVOUtil.error("考试未开始...");
                }else {
                    return ResultVOUtil.success(examPaper);
                }
            }else { //有开始时间和结束时间
                if (now.before(examPaper.getStartTime())){
                    return ResultVOUtil.error("考试未开始...");
                }else if (now.after(examPaper.getEndTime())){
                    return ResultVOUtil.error("考试已经结束...");
                }else {
                    return ResultVOUtil.success(examPaper);
                }
            }

        }

        return ResultVOUtil.error("试卷未发布，请等待...");
    }

    @GetMapping("/findByTitleLike/{title}/{userId}/{page}/{size}")
    public ResultVO findByTitleLike(@PathVariable("title") String title,
                                    @PathVariable("userId") Integer userId,
                                    @PathVariable("page") Integer page,
                                    @PathVariable("size") Integer size){
        Page<ExamPaper> examPapers = examPaperService
                .findByTitleLike("%" + title + "%", userId,page, size);

        return ResultVOUtil.success(examPapers);
    }

    //试卷选人
    @PostMapping("/selectPeople")
    public void selectPeople(@RequestBody ExamUserDTO examUserDTO){
        Integer examPaperId = examUserDTO.getExamPaperId();
        List<Integer> userIds = examUserDTO.getUserIds();
        examUserService.selectPeople(examPaperId,userIds);
    }

    @GetMapping("/peopleNeedFill/{examPaperId}")
    public ResultVO findPeopleByExamPaperId(@PathVariable("examPaperId") Integer examPaperId){
        List<ExamUser> examUserList = examUserService.findAllByExamPaperId(examPaperId);
        return ResultVOUtil.success(examUserList);
    }

    @GetMapping("/NoFillPeople/{examPaperId}")
    public ResultVO findNoFillPeople(@PathVariable("examPaperId") Integer examPaperId){
        List<String> names = examUserService.findFillByExamPaperId(examPaperId, false);
        return ResultVOUtil.success(names);
    }


    @GetMapping("waitToDo/{userId}")
    public ResultVO waitToDo(@PathVariable("userId") Integer userId){
        List<ExamPaperVO> examPaperVOList = examUserService.waitToDo(userId);
        return ResultVOUtil.success(examPaperVOList);

    }

    @GetMapping("/wantModify/{examPaperId}")
    public ResultVO wantModify(@PathVariable("examPaperId") Integer examPaperId){
        ExamPaper examPaper = examPaperService.findById(examPaperId);
        Date now = new Date();
        Date startTime = examPaper.getStartTime();
        if (startTime!=null && now.after(startTime)){ //如果当前时间晚于考试开始时间
            return ResultVOUtil.error("考试已开始,不能修改试卷...");
        }
        return ResultVOUtil.success(null);
    }

}


